<!DOCTYPE HTML>
<html>
<!-- lang="en" -->

<head>
    <meta charset="utf-8" />
    <title>密码强度</title>
    <style type="text/css">
        #pwdStrength {
            height: 30px;
            width: 180px;
            border: 1px solid #ccc;
            padding: 2px;

        }

        .strengthLv1 {
            background: red;
            height: 30px;
            width: 60px;
        }

        .strengthLv2 {
            background: orange;
            height: 30px;
            width: 120px;
        }

        .strengthLv3 {
            background: green;
            height: 30px;
            width: 180px;
        }

        #pwd {
            height: 30px;
            font-size: 20px;
        }

        strong {
            margin-left: 90px;
        }

        #pwd1 {
            color: red;
            margin-top: 5px;
            margin-bottom: 5px;
        }
    </style>
</head>

<body>
    <input type="password" name="pwd" id="pwd" maxlength="16" />
    <div class="pass-wrap">
        <!--<em>密码强度：</em>-->
        <p id="pwd1" name="pwd">密码强度:</p>
        <div id="pwdStrength"></div>
    </div>
</body>

</html>
<script type="text/javascript">
    function PasswordStrength(passwordID, strengthID) {
        this.init(strengthID);
        var _this = this;
        document.getElementById(passwordID).onkeyup = function () {//onkeyup 事件,在键盘按键被松开时发生,进行判断
            _this.checkStrength(this.value);
        }
    };
    PasswordStrength.prototype.init = function (strengthID) {
        var id = document.getElementById(strengthID);
        var div = document.createElement('div');
        var strong = document.createElement('strong');
        this.oStrength = id.appendChild(div);
        this.oStrengthTxt = id.parentNode.appendChild(strong);
    };
    PasswordStrength.prototype.checkStrength = function (val) { //验证密码强度的函数
        var aLvTxt = ['', '低', '中', '高'];//定义提示消息的种类
        var lv = 0; //初始化提示消息为空
        if (val.match(/[a-z]/g)) { lv++; } //验证是否包含字母
        if (val.match(/[0-9]/g)) { lv++; }  // 验证是否包含数字
        if (val.match(/(.[^a-z0-9])/g)) { lv++; } //验证是否包含字母，数字，字符
        if (val.length < 6) { lv = 0; } //如果密码长度小于6位，提示消息为空
        if (lv > 3) { lv = 3; }
        this.oStrength.className = 'strengthLv' + lv;
        this.oStrengthTxt.innerHTML = aLvTxt[lv];
    };
    new PasswordStrength('pwd', 'pwdStrength');
</script>